package chat;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class ControlMain extends JFrame implements ActionListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Socket socket;
	private JTextArea jta,jta1;
	private JButton send;
	private Object message;
    private String[] name={"小明","小张","小李"};;

	public ControlMain() throws IOException {
		// TODO Auto-generated constructor stub
		setTitle("聊天器");
		setSize(600, 600);
		setResizable(false);
		Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
		Dimension framesize = this.getSize();
		int x = (int) screensize.getWidth() / 2 - (int) framesize.getWidth() / 2;
		int y = (int) screensize.getHeight() / 2 - (int) framesize.getHeight() / 2;
		setLocation(x, y);
		setLayout(null);
		setVisible(true);

		jta = new JTextArea();
		jta.setBorder(BorderFactory.createLoweredBevelBorder());
		jta.setCaretPosition(jta.getText().length());
		JScrollPane jsp = new JScrollPane(jta);
		jsp.setSize(565, 340);
		jsp.setLocation(10, 10);
		add(jsp);

		jta1 = new JTextArea();
		jta1.setBorder(BorderFactory.createLoweredBevelBorder());
		JScrollPane jsp1 = new JScrollPane(jta1);
		jsp1.setSize(565, 140);
		jsp1.setLocation(10, 360);
		add(jsp1);

		send = new JButton("Send");
		send.setBounds(380, 515, 80, 30);
		send.addActionListener(this);
		add(send);

		JButton clear = new JButton("Clear");
		clear.setBounds(480, 515, 80, 30);
		clear.addActionListener(this);
		add(clear);
        
		jta1.addKeyListener(new KeyAdapter() {
		    @Override
		    	public void keyPressed(KeyEvent e) {
		    		// TODO Auto-generated method stub
		    		super.keyPressed(e);
		    		int code=e.getKeyCode();
		    		switch (code) {
					case KeyEvent.VK_ENTER:
						Date date=new Date();
			        	DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			        	String time=df.format(date);
			        	message=jta1.getText();
			        	jta.append("我（" + time + "）:\n" + message + "\n");
			        	send();
			        	jta1.setText("");
			        	jta1.setCaretPosition(0);
						break;
					default:
						break;
					}
		    	}	
		});
		
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					send.setEnabled(false);
					ServerSocket server=new ServerSocket(9966);
					jta.append("服务器已启动，等待客户端连接...\n");
					socket = server.accept();
					jta.append(socket.getInetAddress().getHostAddress() + "连接！\n");
					accept1();
					send.setEnabled(true);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();
		
		setDefaultCloseOperation(EXIT_ON_CLOSE);
	}

	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					new ControlMain();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
        String com=e.getActionCommand();
        if(com=="Send"){
        	Date date=new Date();
        	DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        	String time=df.format(date);
        	message=jta1.getText();
        	jta.append("我（" + time + "）:\n" + message + "\n");
        	send();
        	jta1.setText("");
        	jta1.setCaretPosition(0);
        }
        
        if(com=="Clear"){
        	jta1.setText("");
        }
	}
    
	public void accept1() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				while (true) { 
					try { 
						Object message1;
						while(socket.getInputStream()!=null){
							ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
							message1 = ois.readObject();
							Date date=new Date();
							DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
							String time=df.format(date);
							jta.append(name[2] + "（" + time + "）:\n" + message1 + "\n");
						}
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (ClassNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}).start();
	}
	
	public void send(){
		try {
			ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream());
			oos.writeObject(message);
			oos.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
